"""
The MIT License (MIT)
Copyright © 2022 Walkline Wang (https://walkline.wang)
Gitee: https://gitee.com/walkline/micropython-resource-manager

A test unit used to read user resource files on specified partition of MicroPython firmware
"""
import os
import esp32
import math
from libs.fontlib import FontLib

RESOURCE_PARTITION = '/res'


def mount_resource_partition() -> bool:
	try:
		os.umount(RESOURCE_PARTITION)
	except OSError as ose:
		if str(ose) == '[Errno 22] EINVAL':
			pass
		else:
			print(ose)

	res = esp32.Partition.find(esp32.Partition.TYPE_DATA, label='resource')

	if res:
		os.mount(res[0], RESOURCE_PARTITION)
		return True
	else:
		return False

def is_resource_file_exists(filename:str) -> bool:
	try:
		os.stat(f'{RESOURCE_PARTITION}/{filename}')
		return True
	except OSError as ose:
		if str(ose) == '[Errno 2] ENOENT':
			return False
		else:
			raise OSError(ose)

def bitmap_preview(filename):
	with open(filename, 'rb') as bitmap:
		_ = bitmap.readline()
		size = bitmap.readline().replace(b'\n', b'').split(b' ')

		width = int(size[0])
		height = int(size[1])
		bytes_per_row = int(width / 8) + 1

		buffer = bitmap.read()

		for row in range(height):
			for index in range(bytes_per_row):
				data = buffer[row * bytes_per_row + index]
				offset = 8 if (index + 1) * 8 < width else 8 - ((index + 1) * 8 - width)

				print('{:08b}'.format(data)[:offset].replace('0', '.').replace('1', '@'), end='')
			print('')

def chars_preview(fontlib:FontLib, buffer_list:list):
	data_size = fontlib.data_size
	font_height = fontlib.font_height
	bytes_per_row = int(font_height / 8)
	chars_per_row = 120 // font_height

	for char in range(math.ceil(len(buffer_list) / chars_per_row)):
		for count in range(bytes_per_row):
			for col in range(8):
				if count * 8 + col >= font_height: continue
				for buffer in buffer_list[char * chars_per_row:char * chars_per_row + chars_per_row]:
					if len(buffer) < data_size: buffer = bytes(data_size)

					for index in range(count * font_height, count * font_height + font_height):
						data = ''.join(reversed('{:08b}'.format(buffer[index])))
						print('{}'.format(data[col].replace('0', '.').replace('1', '@')), end='')
					print(' ', end='')
				print('')
		print('')


if __name__ == '__main__':
	if mount_resource_partition():
		if is_resource_file_exists('mua.pbm'):
			print('bitmap preview')
			bitmap_preview(f'{RESOURCE_PARTITION}/mua.pbm')

		if is_resource_file_exists('chushibiao.txt'):
			_ = input('\npress any key to continue...')
			print('text preview')

			chushibiao = None
			with open(f'{RESOURCE_PARTITION}/chushibiao.txt') as file:
				chushibiao = file.read()

			print(chushibiao)

			if is_resource_file_exists('chushibiao.bin'):
				_ = input('\npress any key to continue...')
				print('fontlib preview')

				fontlib = FontLib(f'{RESOURCE_PARTITION}/chushibiao.bin')
				fontlib.info()

				_ = input('\npress any key to continue...')
				print('chars data preview')

				chushibiao = chushibiao.replace('\r', '').replace('\n', '')

				buffer_dict = fontlib.get_characters(chushibiao[:20])
				for unicode, buffer in buffer_dict.items():
					print("{}: {}\n".format(chr(unicode), bytes(buffer)), end='')

				buffer_list = []
				for char in chushibiao[:20]:
					buffer_list.append(buffer_dict[ord(char)])

				_ = input('\npress any key to continue...')
				print('chars preview')

				del chushibiao
				del buffer_dict

				chars_preview(fontlib, buffer_list)

				del buffer_list
				del fontlib
	else:
		print('cannot mount resource partition')
